/**
 * 
 */
package com.ssm.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ssm.exception.ExceptionCode;
import com.ssm.exception.SsmException;
import com.ssm.exception.WebException;
import com.ssm.model.Model;
import com.ssm.model.bean.MenuList;
import com.ssm.model.bean.SsmUserRules;
import com.ssm.model.mapper.UserRuleMapper;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * SSM 过滤器(功能 生成菜单,路径导航栏,初始化网站参数)
 * @author 危文涛<245108903@qq.com>
 * @version 2016年2月20日 下午5:29:14
 *
 */
public class SSMFilter extends OncePerRequestFilter {
	
	
	private WebSettingUtil S;
	private String [] noFilter;
	private String errorUrl;
	
	public void setErrorUrl(String errorUrl) {
		this.errorUrl = errorUrl;
	}

	public void setNoFilter(String noFilter)
	{
		if(noFilter.isEmpty()||noFilter==null)
			this.noFilter=new String[]{"login","/static/"};
		else
			this.noFilter=noFilter.split(",");
	}
	
	public SSMFilter() {
		// TODO Auto-generated constructor stub
		this.noFilter=new String[]{"login","/static/"};
		ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
		S=context.getBean(WebSettingUtil.class);
	}
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException,WebException {
		String uri = request.getRequestURI();  
        boolean doFilter = true;  
        for (String s : this.noFilter) 
        {  
        	if (uri.indexOf(s) != -1) {  
               doFilter = false;  
               break;
             }  
         }
        if(doFilter)
		{
        	long start=System.currentTimeMillis();
        	getMenu(request);
        	getBreadcrumb(request);
        	InitWebSetting(request);
        	System.out.println(System.currentTimeMillis()-start);
        	doFilter(request, response, filterChain);
		}
        else
        {
        	doFilter(request, response, filterChain);
        }
	}
	
	protected void InitWebSetting(HttpServletRequest request) {
		
		request.setAttribute("DEFAULT_WEB_NAME", S.getString("default_web_name"));
		
		
	}

	
	protected void getMenu(HttpServletRequest request) {
		
		MenuList menuList=(MenuList) EhcacheUtil.get("HOMEINFO","MENU_LIST");
		if(menuList==null)
		{
		ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
    	Model M=(Model) context.getBean(Model.class);
		UserRuleMapper userRuleMapper=M.getMapper(UserRuleMapper.class);
		Example example=new Example(SsmUserRules.class,true);
		Criteria criteria=example.createCriteria();
		criteria.andCondition("rank>0");
		criteria.andCondition("status=","1");
		example.selectProperties("id","link","title","pid","rank");
		List<SsmUserRules> ruleList=userRuleMapper.selectByExample(example);
		SsmUserRules oneRules=ruleList.remove(0);
		menuList=new MenuList();
		menuList.setName(oneRules.getTitle());
		menuList.setLink(oneRules.getLink());
		List<MenuList> menuLists=ListRule2Tree(ruleList, 1);
		if(menuLists.size()>0)
		{
			menuList.setHasNext(true);
			menuList.setChildrenList(menuLists);
		}
		EhcacheUtil.put("HOMEINFO","MENU_LIST",menuList);
		request.setAttribute("MENU_LIST",menuList);
		}
		else
			request.setAttribute("MENU_LIST",menuList);
		
	}
	
	private List<MenuList> ListRule2Tree(List<SsmUserRules> list,int root)
	{
		List<MenuList> temp=new ArrayList<MenuList>();
		for (SsmUserRules ssmUserRules : list) {
			if(ssmUserRules.getPid()==root)
			{
				MenuList menuList=new MenuList();
				menuList.setName(ssmUserRules.getTitle());
				menuList.setLink(ssmUserRules.getLink());
				List<MenuList> next=ListRule2Tree(list,ssmUserRules.getId());
				if(next.size()>0)
				{
					menuList.setHasNext(true);
					menuList.setChildrenList(next);
				}
				temp.add(menuList);
			}
		}
		return temp;
	}

	protected void getBreadcrumb(HttpServletRequest request)
	{
		
		ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
    	Model M=(Model) context.getBean(Model.class);
		UserRuleMapper userRuleMapper=M.getMapper(UserRuleMapper.class);
		SsmUserRules rules=new SsmUserRules();
		rules.setLink(request.getServletPath());
		List<SsmUserRules> list=userRuleMapper.select(rules);
		List<SsmUserRules> need=new ArrayList<SsmUserRules>();
		if(list.size()>0)
		{
			need.add(list.get(0));
			
			if(EhcacheUtil.get("RULELIST",list.get(0).getPid())==null)
			{
				rules=userRuleMapper.selectByPrimaryKey(list.get(0).getPid());
				EhcacheUtil.put("RULELIST", list.get(0).getPid(), rules);
			}
			else {
				rules=(SsmUserRules) EhcacheUtil.get("RULELIST",list.get(0).getPid());
			}
			while(rules.getId()!=1)
			{
				need.add(rules);
				
				if(EhcacheUtil.get("RULELIST",rules.getPid())==null)
				{
					rules=userRuleMapper.selectByPrimaryKey(rules.getPid());
					EhcacheUtil.put("RULELIST",rules.getPid(), rules);
				}
				else
					rules=(SsmUserRules) EhcacheUtil.get("RULELIST",rules.getPid());
			}
			need.add(rules);
		}
		else {
			throw new SsmException(ExceptionCode.NOT_FIND_BREADCRUMB);
		}
		List<SsmUserRules> temp=new ArrayList<SsmUserRules>();
		for(int i=need.size()-1;i>=0;i--)
		{
			temp.add(need.get(i));
		}
		request.setAttribute("BREADCRUMB",temp);
	}
	
	
	
}
